package com.slfx.openapi.client.controller;

import com.alibaba.fastjson.JSON;
import com.slfx.openapi.client.config.OpenApiConfig;
import com.slfx.openapi.client.entity.ShortUrl;
import com.slfx.openapi.client.util.HttpCallUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zengqingfa
 * @className ShortUrlController
 * @description
 * @create 2022/9/25 16:42
 */
@RestController
@Slf4j
public class OpenApiClientController {


    @Resource
    private HttpCallUtil httpCallUtil;
    @Resource
    private OpenApiConfig openApiConfig;

    /**
     * 根据ID获取
     *
     * @param id
     * @return
     */
    @GetMapping("/client/shortUrl/getById")
    public ShortUrl getById(@RequestParam("id") Long id) {
        ShortUrl shortUrl = null;
        Map<String, Object> paramMap = new HashMap<>();
        try {
            String getByIdUrl = openApiConfig.getGetByIdUrl();
            String url = getByIdUrl + "?id=" + id;
            String s = httpCallUtil.sendOpenApiGet(url, paramMap);
            //通过json转换
            shortUrl = JSON.parseObject(s, ShortUrl.class);
        } catch (Exception e) {
            log.error("调用开放平台失败：{}", e);
        }
        return shortUrl;
    }


    /**
     * @param shortUrl
     * @return
     */
    @PostMapping("/client/shortUrl/list")
    public List<ShortUrl> list(@RequestBody ShortUrl shortUrl) {
        List<ShortUrl> shortUrls = null;
        try {
            String s = httpCallUtil.sendOpenApiPost(openApiConfig.getListUrl(), JSON.toJSONString(shortUrl));
            //通过json转换
            shortUrls = JSON.parseArray(s, ShortUrl.class);
        } catch (Exception e) {
            log.error("调用开放平台失败：{}", e);
        }
        return shortUrls;
    }
}